package org.jsbd.boss.task;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import com.zhexinit.proxy.http.util.Md5Util;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.jsbd.boss.bto.AppInfo;
import org.jsbd.boss.bto.BatteryInfo;
import org.jsbd.boss.bto.HttpResult;
import org.jsbd.boss.common.redis.RedisClient;
import org.jsbd.boss.dao.IMobileClientDAO2;
import org.jsbd.boss.domian.IpRange;
import org.jsbd.boss.domian.WifiInfo;
import org.jsbd.boss.domian.channel.CameraInfo;
import org.jsbd.boss.domian.channel.MobileClient;
import org.jsbd.boss.domian.channel.SdkClientInfo;
import org.jsbd.boss.domian.channel.UserClientInfo;
import org.jsbd.boss.mq.UserLogManager;
import org.jsbd.boss.service.ClientManager;
import org.jsbd.boss.service.ICameraService;
import org.jsbd.boss.service.IWifiInfoService;
import org.jsbd.boss.service.impl.TaskUtil;
import org.jsbd.boss.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import edu.hziee.common.queue.DelayExecuteBuffer;

/**
 * @desc
 * @Date 2018/8/10 17:49
 * @Author xupengcheng [xupengcheng@zhexinit.com]
 */
public class NewUserClientTask implements Runnable, Serializable{

    private static final long serialVersionUID = 1L;

    public static final Logger LOGGER = LoggerFactory.getLogger(NewUserClientTask.class);

    private HttpResult httpResult;
    private IpRange ipRange;

    private RedisClient redisClient;

    private DelayExecuteBuffer newUserClientBatchInsertBuffer;

    public NewUserClientTask(HttpResult httpResult, IpRange ipRange) {
        this.httpResult = httpResult;
        this.ipRange = ipRange;
    }


    @Override
    public void run() {
        try {
            String imsi = httpResult.getImsi();
            String hsman = httpResult.getHsman();
            String hstype = httpResult.getHstype();
            String imei = httpResult.getImei();
            String build_version = httpResult.getBuild_version();
            String board = httpResult.getBoard();
            String productDevice = httpResult.getProductDevice();
            String kernelVersion = httpResult.getKernelVersion();
            redisClient = SpringContextUtils.getBean("redisClient");
            String userCacheKey = CacheKey.ONLINE_IMSI_RECORD + "_NEW";
            String mobileCacheKey = CacheKey.MOBILE_CLIENT_HASH;
            Long userTime = (Long) redisClient.getHash(userCacheKey, imsi);
            String fieldKey = hsman.toLowerCase() + hstype.toLowerCase() + build_version + board + productDevice + kernelVersion;
            String md5Key = Md5Util.md5(fieldKey);

            //兼容老数据
            Long mobileTime = 0L;
            Object mobileValue = redisClient.getHash(mobileCacheKey, md5Key);
            if(mobileValue != null){
                mobileTime = Long.parseLong(mobileValue.toString());
            }
            long now = System.currentTimeMillis();
            if (userTime != null && now - userTime < 86400 * 1000 && mobileTime != null && now - mobileTime < 86400 * 1000) {
                return;
            }
            SdkClientInfo sdkClientInfo = NewUserClientUtil.checkClient(httpResult, redisClient, ipRange);
            if(sdkClientInfo == null){
                LOGGER.warn("新用户参数校验失败1 {} {} {} {}", new String[]{imsi, hsman, hstype, imei});
            }else{
            	UserLogManager.addSaveUserSuccLog(httpResult);
                String clientJsonData = JSONObject.toJSONString(sdkClientInfo);
                collectUserClient(sdkClientInfo, userTime, clientJsonData);
                collectMobileClient(mobileTime, clientJsonData, md5Key);
            }
        } catch (Exception e) {
            LOGGER.error("用户信息解析失败 {} {} {}", new Object[]{httpResult.getImsi(), httpResult.getUuid(), e});
        }
    }


    private void collectMobileClient(Long mobileTime, String clientJsonData, String fileName) throws Exception {
        if(mobileTime != null && System.currentTimeMillis() - mobileTime < 86400 * 1000){
            return;
        }

        String ossFileNameUrl = TaskUtil.getMobileFileName(fileName);
        byte[] zipFileDatas = ZipUtil.zipFile(clientJsonData, fileName);
        OssUtils.uploadFile("webmeng", ossFileNameUrl, zipFileDatas);
        //收集手机型号

        IMobileClientDAO2 mobileClientDAO2 = SpringContextUtils.getBean(IMobileClientDAO2.class);
        MobileClient mobileClient = new MobileClient();
        mobileClient.setHsman(httpResult.getHsman());
        mobileClient.setHstype(httpResult.getHstype());
        mobileClient.setBuildVersion(httpResult.getBuild_version());
        mobileClient.setBoard(httpResult.getBoard());
        mobileClient.setKernelVer(httpResult.getKernelVersion());
        mobileClient.setProductDevice(httpResult.getProductDevice());
        mobileClient.setOssUrl(ossFileNameUrl);
        mobileClientDAO2.insertMobileClient(mobileClient);
        redisClient.putHash(CacheKey.MOBILE_CLIENT_HASH, fileName, System.currentTimeMillis());
    }

    private void collectUserClient(SdkClientInfo sdkClientInfo, Long userTime, String clientJsonData){
        if(userTime != null && System.currentTimeMillis() - userTime < 86400 * 1000){
            return;
        }

        Map<String, String> dataMap = new HashMap<>();
        dataMap.put("data", clientJsonData);
        dataMap.put("imsi", sdkClientInfo.getImsi());
        ExtraParamOssUploadTask.addNewClientTask(dataMap);

        UserClientInfo userClientInfo = new UserClientInfo();
        userClientInfo.setImsi(httpResult.getImsi());
        userClientInfo.setImei(httpResult.getImei());
        userClientInfo.setHsman(httpResult.getHsman());
        userClientInfo.setHstype(httpResult.getHstype());
        userClientInfo.setProvince(ipRange.getProvinceId());
        userClientInfo.setCarrier(ClientManager.checkImsi(httpResult.getImsi()));
        userClientInfo.setSdkUuid(httpResult.getUuid());
        userClientInfo.setKernelVer(httpResult.getKernelVersion());
        userClientInfo.setBuildVersion(httpResult.getBuild_version());
        userClientInfo.setRelease(sdkClientInfo.getVersion_release());
        userClientInfo.setSdkVersion(httpResult.getSdkVerName());
        LOGGER.warn("用户信息解析成功 {} {} ", httpResult.getImsi(), httpResult.getUuid());
        newUserClientBatchInsertBuffer = SpringContextUtils.getBean("newUserClientBatchInsertBuffer");
        newUserClientBatchInsertBuffer.add(userClientInfo);
        redisClient.putHash(CacheKey.ONLINE_IMSI_RECORD + "_NEW", userClientInfo.getImsi(), System.currentTimeMillis());
    }


}
